const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');
const pi = require('../../utils/piexif.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    files: [],
    infoJson: {},
    dateData: [],
    showIndex: null,
    height:'',
    boxheight:'',
    editJsonIndex: 0,
    longArray:['东经','西经'],
    latArray:['北纬','南纬'],
    longArrayIndex: 0,
    latArrayIndex: 0,
    editType: '',
    editInputJson: {},
    zeroth : {},
    exif : {},
    gps: {},
    stableExifObj:{},
    buttonText: '写入修改信息',
  },

  bindLongChange(e){
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      longArrayIndex: e.detail.value
    })

    var json = this.data.editInputJson
    json.value2 = this.data.longArray[e.detail.value]
    this.setData({
      editInputJson: json
    })
    console.log(JSON.stringify(this.data.editInputJson))
  },
  bindLatChange(e){
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      latArrayIndex: e.detail.value
    })
    var json = this.data.editInputJson
    json.value2 = this.data.latArray[e.detail.value]
    this.setData({
      editInputJson: json
    })
    console.log(JSON.stringify(this.data.editInputJson))
  },

  onEditTime: function(e){
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var json = this.data.editInputJson
    json.value2 = e.detail.value+":00"
    this.setData({
      editInputJson: json
    })
  },

  onEditDate: function(e){
    console.log('picker发送选择改变，携带值为', e.detail.value)

    var json = this.data.editInputJson
    json.value1 = e.detail.value.replaceAll('-',':')
    this.setData({
      editInputJson: json
    })
  },

  onEditString(e){
    var inputJson = this.data.editInputJson
    inputJson.value1 = e.detail.value
    this.setData({
      editInputJson: inputJson
    })
    console.log('-----------'+JSON.stringify(this.data.editInputJson) )
  },

  openPopup(e){
    var editType = ''
    var index = e.currentTarget.dataset.index
    var inputJson = {}
    inputJson.index = index
    if(index == 0 || index == 1 || index == 2){
      editType = 'string'
    }
    if(index == 3 || index == 4 || index == 5){
      editType = 'date'
      
      inputJson.value1 = this.data.dateData[index].value.split(' ')[0]
      try{
        inputJson.value2 = this.data.dateData[index].value.split(' ')[1]
      }catch(e){
        inputJson.value2 = ''
      }
      
    }
    if(index == 6){
      editType = 'gps_lat'
      inputJson.value2 = this.data.latArray[this.data.latArrayIndex]
    }

    if(index == 7){
      editType = 'gps_long'
      inputJson.value2 = this.data.longArray[this.data.longArrayIndex]
    }


    var that = this;

    const query = wx.createSelectorQuery()
    query.select('#container').boundingClientRect();
    query.exec(function (res) {
        that.setData({
          boxheight: res[0]['height']
        });
    })


    this.setData({
      editType: editType,
      showIndex:1,
      editJsonIndex:e.currentTarget.dataset.index,
      editInputJson: inputJson
    })
    console.log(this.data.editInputJson)
  },

  saveImage(){
    wx.showLoading({
      title: '加载中',
    })
    var that = this
    console.log(this.data.files[0])
    wx.saveImageToPhotosAlbum({
      filePath: that.data.files[0],
      success: function(data) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '保存成功，请前往手机相册查看',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('------------返回上一级-----------')
              wx.navigateBack()
            } else if (res.cancel) {
              //点击取消按钮
            }
          }
        })
      },
      fail: function(){
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '保存失败，请重试',
          showCancel: false,
        })
      }

    })
  },

  onTouchSava(that){
    wx.getSetting({
        success(res) {
            if (!res.authSetting['scope.writePhotosAlbum']) {
                wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                      that.saveImage()
                    },
                    fail() { 
                    } 
                });
            } else {
              that.saveImage()
            }
        }
    });
  },

  accountLogin: function(){
    var that = this
    if(this.data.buttonText == '写入成功，点击保存'){
      that.onTouchSava(that)
      return
    }

    this.setData({
      buttonText: '写入中'
    })
    wx.showLoading({
      title: '写入时间较长',
    })
    var exifObj = {"0th":this.data.zeroth, "Exif":this.data.exif, "GPS":this.data.gps};
    console.log(exifObj)

    var stableExifObj = this.data.stableExifObj,exifObj
    console.log(stableExifObj)

    stableExifObj['0th'] = Object.assign(stableExifObj['0th'],exifObj['0th'])
    stableExifObj['Exif'] = Object.assign(stableExifObj['Exif'],exifObj['Exif'])
    stableExifObj['GPS'] = Object.assign(stableExifObj['GPS'],exifObj['GPS'])

    console.log(stableExifObj)

    
    var exifbytes = pi.dump(stableExifObj);
    
    var path = that.data.files[0]
    let sBase64 = 'data:image/jpg;base64,' + wx.getFileSystemManager().readFileSync(path, 'base64')
    var inserted = pi.insert(exifbytes, sBase64);

    try{
      pi.load(inserted)
    }catch(e){
      wx.hideLoading()
      wx.showModal({
        title: '提示',
        content: '输入的数值不符合规范，请重新填写',
        showCancel: false,
      })
      this.setData({
        buttonText: '写入修改信息'
      })

      console.log(e)
      return;
    }
    
    //console.log(inserted)

    var base64data = inserted;
    const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
    if (!format) {
      return (new Error('ERROR_BASE64SRC_PARSE'));
    }
    var FILE_BASE_NAME = 'tmp_base64src';
    var save = wx.getFileSystemManager();
    const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
    const buffer = wx.base64ToArrayBuffer(bodyData);
    save.writeFile({
      filePath,
      data: buffer,
      encoding: 'binary',
      success(res) {
        console.log( "res",res )
        //options.path
        var options = {}
        options.path = filePath
        options.ok = true
        that.onLoad(options)
        wx.hideLoading()
        that.setData({
          buttonText: '写入成功，点击保存'
        })
      },
      fail() {
        wx.hideLoading()
        that.setData({
          buttonText: '写入失败，点击重写'
        })
      },
    });
  },

  confirmPopup(){
    var zeroth = this.data.zeroth;
    var exif = this.data.exif;
    var gps = this.data.gps
    var json = this.data.editInputJson
    var info = this.data.dateData
    console.log(JSON.stringify(json) )
    if(json.index == 0){
      console.log('-----------')
      zeroth[pi.ImageIFD.Make] = json.value1;
      info[json.index].value = json.value1;
    }
    if(json.index == 1){
      zeroth[pi.ImageIFD.Model] = json.value1;
      info[json.index].value = json.value1;
    }
    if(json.index == 2){
      zeroth[pi.ImageIFD.Software] = json.value1;
      info[json.index].value = json.value1;
    }
    if(json.index == 3){
      exif[pi.ExifIFD.DateTimeOriginal] = json.value1+' '+json.value2;
      info[json.index].value = json.value1+' '+json.value2;
    }
    if(json.index == 4){
      exif[pi.ExifIFD.DateTimeDigitized] = json.value1+' '+json.value2;
      info[json.index].value = json.value1+' '+json.value2;
    }
    if(json.index == 5){
      zeroth[pi.ImageIFD.DateTime] = json.value1+' '+json.value1;
      info[json.index].value = json.value1+' '+json.value2;
    }
    if(json.index == 6){
      gps[pi.GPSIFD.GPSLatitudeRef] = json.value2 == '北纬' ? 'N' : 'S';
      gps[pi.GPSIFD.GPSLatitude] = pi.GPSHelper.degToDmsRational(json.value1);
      info[json.index].value = json.value1+' '+json.value2;
    }
    if(json.index == 7){
      gps[pi.GPSIFD.GPSLongitudeRef] = json.value2 == '东经'? 'E' : 'W';
      gps[pi.GPSIFD.GPSLongitude] = pi.GPSHelper.degToDmsRational(json.value1);
      info[json.index].value = json.value1+' '+json.value2;
    }
  
    console.log(info)
    this.setData({
      showIndex:null,
      dateData: info
    })
  },

  //关闭弹窗
  closePopup(){
    this.setData({
      showIndex: null,
      
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.path){
      console.log(options.path)
      this.setData({
        files: [options.path]
      })

      wx.showLoading({
        title: '读取时间较长',
      })

      var that = this;
      wx.getSystemInfo({
        success: (result) => {
          that.setData({
            height: result.windowHeight
          });
        },
      })
      var path = that.data.files[0]
      console.log(path)
      let sBase64 = 'data:image/jpg;base64,' + wx.getFileSystemManager().readFileSync(path, 'base64')
      var exifObj = pi.load(sBase64)
      that.setData({
        stableExifObj: exifObj
      })

      var json = {}
      for (var ifd in exifObj) {
        if (ifd == "thumbnail") {
            continue;
        }
        
        for (var tag in exifObj[ifd]) {
            console.log("  " + pi.TAGS[ifd][tag]["name"] + ":" + exifObj[ifd][tag]);
            json[pi.TAGS[ifd][tag]["name"]] = exifObj[ifd][tag]
        }
      }
      console.log(exifObj)
      var datas = new Array()
      datas.push({"name":"设备制造商","value":this.getJsonValue(json.Make)})
      datas.push({"name":"设备型号","value":this.getJsonValue(json.Model)})
      datas.push({"name":"设备固件版本","value":this.getJsonValue(json.Software)})
      datas.push({"name":"按下快门时间","value":this.getJsonValue(json.DateTimeOriginal)})
      datas.push({"name":"生成照片时间","value":this.getJsonValue(json.DateTimeDigitized)})
      datas.push({"name":"设备时间","value":this.getJsonValue(json.DateTime)})
      
      if(json.GPSLatitude!=null && json.GPSLatitude!=undefined){
        var latText = pi.GPSHelper.dmsRationalToDeg(json.GPSLatitude)
        latText = latText +' '+(json.GPSLatitudeRef === 'N'?'北纬':'南纬')
        datas.push({"name":"拍摄地点-纬度","value": latText})
      }else{
        datas.push({"name":"拍摄地点-纬度","value": "拍摄设备未写入"})
      }
      if(json.GPSLongitude!=null && json.GPSLongitude!=undefined){
        var longText = pi.GPSHelper.dmsRationalToDeg(json.GPSLongitude)
        longText = longText +' '+(json.GPSLongitudeRef === 'E'?'东经':'西经')
        datas.push({"name":"拍摄地点-经度","value": longText})
      }else{
        datas.push({"name":"拍摄地点-经度","value": "拍摄设备未写入"})
      }
      datas.push()
      
      
      console.log(datas)
      this.setData({
        dateData: datas
      })
      wx.hideLoading()

      if(options.ok!=null && options.ok!=undefined && options.ok == true){
        wx.showModal({
          title: '提示',
          content: '生成成功，点击页面底部按钮可保存到手机相册',
          showCancel: false,
          confirmText: '知道了',
          success(res){
            wx.pageScrollTo({
              selector: '#button',
            });
          }
        })
      }
    }
  },

  getJsonValue(value){
    if(value == null || value == undefined){
      return '拍摄设备未写人'
    }
    return value;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})